package listStudy;

import common.utils.ListNode;

public class FindFirstCommonNode {

    public static void main(String[] args) {

    }

    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        if (pHead1 == null && pHead2 == null){
            return null;
        }
        ListNode ptr1 = pHead1;
        ListNode ptr2 = pHead2;
        while (ptr1 != null && ptr2 != null){
            ptr1 = ptr1.next;
            ptr2 = ptr2.next;
        }
        if (ptr1 == null){
            ptr1 = pHead2;
        }
        if (ptr2 == null){
            ptr2 = pHead1;
        }
        while (ptr1 != null && ptr2 != null){
            ptr1 = ptr1.next;
            ptr2 = ptr2.next;
        }
        if (ptr1 == null){
            ptr1 = pHead2;
        }
        if (ptr2 == null){
            ptr2 = pHead1;
        }
        while (ptr1 != null && ptr2 != null){
            if (ptr1 == ptr2){
                return ptr1;
            }
            ptr1 = ptr1.next;
            ptr2 = ptr2.next;
        }
        return null;
    }
}
